package com.vanke.devops.domain.domain.endpoints;

import com.vanke.core.util.JsonUtil;
import com.vanke.devops.domain.DomainConstants;
import com.vanke.devops.domain.manager.aliyun.bean.Node;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ExecutorService;

/**
 * @author 陈景阳
 * @since 2018/4/16
 */
@Slf4j
@ServerEndpoint("/endpoints/item")
@Component
public class EndpointsItemWebSocket implements ApplicationContextAware{

    private static IEndpointsService endpointsService;

    private Session session;

    private String instanceId;

    private boolean isClose = true;

    private Thread thread;

    public EndpointsItemWebSocket(){
        thread = new Thread(() -> this.task());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        endpointsService = applicationContext.getBean(IEndpointsService.class);
    }

    @OnOpen
    public void onOpen(Session session){
        log.info("on open: {}",session.getId());
        this.session = session;
        this.isClose = false;
        thread.start();
    }

    @OnClose
    public void onClose(){
        this.isClose = true;
    }


    @OnMessage
    public void onMessage(String message,Session session){
        if(!DomainConstants.WEB_SOCKET_HEART.equals(message)){
            this.instanceId = message;
        }
    }

    private void sendMessage(String message){
        try {
            this.session.getBasicRemote().sendText(message);
        }catch (IOException e){
            e.printStackTrace();
            this.isClose = true;
        }
    }

    private void task(){
        while (true){
            if(this.isClose){
                break;
            }
            try {
                Node node = endpointsService.getNodeInfo(instanceId);
                if(node != null){
                    this.sendMessage(JsonUtil.toJson(node));
                }
            }catch (Exception ex){
            }

            try {
                Thread.sleep(20 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
